package com.example.hookapp.base;

import android.content.Context;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import androidx.appcompat.widget.LinearLayoutCompat;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ScreenUtils;

public abstract class BaseFloatHookView extends LinearLayoutCompat {
    protected Context context;
    private float touchSlop;

    public BaseFloatHookView(Context context) {
        super(context);
        this.context = context;
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        init();
    }

    private void init() {
        MarginLayoutParams layoutParams = new MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = ConvertUtils.dp2px(80);
        setLayoutParams(layoutParams);
        setOrientation(LinearLayoutCompat.VERTICAL);
        setBackgroundColor(0xCC000000);
        setPadding(ConvertUtils.dp2px(12), ConvertUtils.dp2px(12), ConvertUtils.dp2px(12), ConvertUtils.dp2px(12));
    }

    private boolean canMove = true;

    protected void setCanMove(boolean canMove) {
        this.canMove = canMove;
    }

    protected int exceptTopHeight() {
        return 0;
    }

    private boolean isExceptMove;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = ev.getY();
                isExceptMove = downY < exceptTopHeight();
                break;
            case MotionEvent.ACTION_MOVE:
                if (!canMove && !isExceptMove) {
                    return super.onInterceptTouchEvent(ev);
                }

                if (Math.abs(downY - ev.getY()) > touchSlop) {
                    downY = ev.getY();
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    private float downY;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!canMove && !isExceptMove) {
            return super.onTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                float offset = ev.getY() - downY;
                float y = getY() + offset;
                if (y <= 0) {
                    y = 0;
                }
                if (y > ScreenUtils.getScreenHeight() - getHeight()) {
                    y = ScreenUtils.getScreenHeight() - getHeight();
                }
                setY(y);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }
}
